<?php

namespace app\model\order;

use app\base\BaseModel;
use think\facade\Db;

/**
 * 订单发货记录
 * 模型-OrderItemLogisticsModel
 * Class OrderItemLogisticsModel
 * @package app\model
 */
class OrderItemLogisticsModel extends BaseModel
{

    protected $name = 'order_item_logistics';

    /**
     * 添加物流
     * @param $data
     * @param $order_type  send发货,return退货,change 换货
     * @param int $operate 0平台 ,1代理商，2买家
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public static function addLogistics($data, $order_type, $operate = 0)
    {
        $in_data = [
            'order_id' => $data['order_id'],
            'order_item_info' => json_encode($data['order_item_info']),
            'order_type' => $order_type,
            'operate' => $operate,
            'logistics_name' => $data['logistics_name'],
            'logistics_code' => $data['logistics_code'],
            'logistics_number' => $data['logistics_number'],
            'update_time' => time(),
            'create_time' => time()
        ];
        Db::startTrans();
        $ret = self::insert($in_data);
        if ($ret !== false) {
            $order_item_model = new OrderItemModel();
            $order_item_model->sendItemEnd($data['order_id'], $data['order_item_info']);
            Db::commit();
            $return_data = [
                'code' => 1,
                'msg' => "发货成功"
            ];
            return $return_data;
        }
        Db::rollback();
        $return_data = [
            'code' => 0,
            'msg' => "发货失败"
        ];
        return $return_data;
    }

    /**
     * 获取物流信息数据
     * @param $order_id
     * @return array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getChildInfo($order_id)
    {
        //订单项
        $data = $this->where("order_id", $order_id)->select();
        if (empty($data)) {
            return [];
        }
        $data = $data->toArray();
        foreach ($data as &$value) {
            $value['order_item_info'] = json_decode($value['order_item_info'], true);
        }
        return $data;
    }

}
